package com.zsrd.auth.core;

import cn.dev33.satoken.stp.StpUtil;
import com.zsrd.system.domain.SysUser;

import java.lang.reflect.Field;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <pre>
 *
 * </pre>
 *
 * @author sunjiyong
 * @since 2023/12/8 14:05
 */
public class UserInfoUtil {

    // 登录接口，什么也不传，通过token获取用户信息
    public static Map<String, Object> userinfo() {
        Map<String, Object> userInfo = new HashMap<>();
        SysUser sysUser = (SysUser) StpUtil.getSession().get(Constants.CURRENT_USER);
        if (sysUser == null) {
            throw new RuntimeException("获取用户信息失败！");
        } else {
            //获取用户详细信息
            userInfo = object2Map(sysUser);
        }
        return userInfo;
    }

    /**
     * 根据当前用户获取绑定的角色
     *
     * @return
     */
    public static List<String> getUserRole() {
        List<String> roleList = StpUtil.getRoleList();
        return roleList;
    }


    /**
     * 实体对象转成Map
     *
     * @param obj 实体对象
     * @return
     */
    public static Map<String, Object> object2Map(Object obj) {
        Map<String, Object> map = new HashMap<>();
        if (obj == null) {
            return map;
        }
        Class clazz = obj.getClass();
        Field[] fields = clazz.getDeclaredFields();
        try {
            for (Field field : fields) {
                field.setAccessible(true);
                map.put(field.getName(), field.get(obj));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }
}
